import { computed, ref } from 'vue'

import { catchFn } from '@/libs/common'
import { createQuiz, getQuizQuestion, getQuizResult, sendQuizAnswer } from '../../api'
import { topMessage } from '@/components/TopMessage/data'
import { result } from '../result/data'

/** 会话ID */
let sessionId = ''
/** 测评类型Code */
const typeCode = 'career'

/** 当前题目 */
const curQuestion = ref<T_Question>()
/** 题目序号 */
const curQuestionIdx = ref(0)
/** 题目总数 */
const questionCount = ref(0)
/** 回答列表 */
let questionList: T_Question[] = []

/** 当前回答 */
const curAnswerIdx = ref(-1)
/** 回答列表 */
let answerList: number[] = []

/** 答题进度 */
const progressValue = computed(
  () =>
    (questionCount.value > 0
      ? Math.floor(((curQuestionIdx.value + 1) / questionCount.value) * 100)
      : 0) + '%',
)

export { typeCode, curQuestion, curQuestionIdx, questionCount, curAnswerIdx, progressValue }

/**
 * 开始测试
 */
const start = () =>
  catchFn(async () => {
    const { data } = await createQuiz(typeCode)

    sessionId = data.sessionId

    questionList[curQuestionIdx.value] = data.firstQuestion
    curQuestion.value = data.firstQuestion
    questionCount.value = data.qustionsCount
  })

/**
 * 上一题
 */
const pre = async () => {
  curQuestion.value = undefined

  await new Promise(resolve => setTimeout(resolve, 100))

  curQuestion.value = questionList[--curQuestionIdx.value]
  curAnswerIdx.value = answerList[curQuestionIdx.value]
}

/**
 * 下一题
 */
const next = () => {
  const ans = curQuestion.value?.options[curAnswerIdx.value]

  if (!ans) {
    topMessage.warn('请作答')
    return
  }

  answerList[curQuestionIdx.value] = curAnswerIdx.value

  catchFn(
    async () => {
      const { data } = await sendQuizAnswer(sessionId, curQuestion.value!.id, ans.value)

      if (curQuestionIdx.value + 1 === questionCount.value) {
        // 提交
        const { data } = await getQuizResult({ sessionId, typeCode })

        result.value = data.loveResult

        uni.redirectTo({ url: '/pages/quiz/career/result/index' })

        return
      }

      // 下一题
      let q = questionList[++curQuestionIdx.value]

      if (q) curAnswerIdx.value = answerList[curQuestionIdx.value] || -1
      else {
        q = (await getQuizQuestion(sessionId, data.nextQuestionId)).data
        questionList[curQuestionIdx.value] = q
        curAnswerIdx.value = -1
      }

      curQuestion.value = q
    },
    { disableLoading: true },
  )
}

/**
 * 还原状态
 */
const clear = () => {
  sessionId = ''

  curQuestion.value = undefined
  questionCount.value = 0
  curQuestionIdx.value = 0
  questionList = []

  curAnswerIdx.value = -1
  answerList = []
}

export { start, pre, next, clear }
